import React, { Component } from 'react';
import { connect } from 'react-redux';
import { CommonTable } from 'components';
import { bindActionCreators } from 'redux';
import { Icon, Tooltip, Button } from 'antd';
import moment from 'moment';
import { overdueListAction } from './index';
import SearchList from './SearchList/SearchList';
import styles from './OverdueList.less';
import { UrgePersonModal } from '../OverdueOrderDistribute';
import {message} from "antd/lib/index";
import FormDemo from './FormDemo'
import { axios } from 'utils';
// new
import OverdueOrderUrgeReqList from './overdueOrderUrgeReqList/overdueOrderUrgeReqList'

//转换参数格式
// const convertParams = (obj) => {
//     const { time, phoneNo, name, orderNo, orderStatus, person } = obj;
//     const isArr = Array.isArray(time) && time.length > 0;
//     return {
//         fstartTime: isArr ? time[0].format('YYYY-MM-DD HH:mm:ss') : '',
//         fendTime: isArr ? time[1].format('YYYY-MM-DD HH:mm:ss') : '',
//         status: orderStatus,
//         userPhone: phoneNo,
//         userTrueName: name,
//         orderNo,
//         collectorId: person
//     };
// }

const statusObj = {
    "0": '逾期中',
    "1": '已结清',
    "2": '已展期'
}

class OverdueList extends Component{
    constructor(props) {
        super(props);
        this.state = {
            breaksVisible: false,
            record: {
                userTrueName: '',
                userPhone: '',
                orderNo: '',
                deviceMoney: '',
                payable: '',
                payMoney: '',
                reduceAmount: '',
                remark: '',
                // 
                isOrderModalView: false,
            }
        };
        const _this = this;
        this.convertParams = (obj) => {
            const { personType } = this.props;
            let key = personType === 'group' ? 'departmentId' : 'collectorId';
            const { time, phoneNo, name, orderNo, orderStatus, person, overdueDay } = obj;
            const isArr = Array.isArray(time) && time.length > 0;
            return {
                fstartTime: isArr ? time[0].format('YYYY-MM-DD HH:mm:ss') : '',
                fendTime: isArr ? time[1].format('YYYY-MM-DD HH:mm:ss') : '',
                status: orderStatus,
                userPhone: phoneNo,
                userTrueName: name,
                orderNo,
                [key]: person,
                overdueDay 
            };
        }
        this.columns = [
            {
                title: '分配时间',
                dataIndex: 'distributionTime',
                key: 'distributionTime',
                render(text) {
                    return moment(Number(text) * 1000).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            { title: '订单号', dataIndex: 'orderNo', key: 'orderNo' },
            { title: '姓名', dataIndex: 'userTrueName', key: 'userTrueName' },
            // { title: '手机型号', dataIndex: 'deviceModel', key: 'deviceModel' },
            // { title: '手机号', dataIndex: 'userPhone', key: 'userPhone' },
            { title: '借款金额(元)', dataIndex: 'lendMoney', key: 'lendMoney' },
            // { title: '展期次数', dataIndex: 'lengNum', key: 'lengNum' },
            { title: '应还金额(元)', dataIndex: 'payable', key: 'payable' },
            { title: '已还金额(元)', dataIndex: 'payMoney', key: 'payMoney' },
            { title: '减免金额(元)', dataIndex: 'reduceAmount', key: 'reduceAmount'},
            {
                title: '订单状态',
                dataIndex: 'status',
                key: 'status',
                render(text) {
                    return statusObj[text] || '';
                }
            },
            {
                title: '催收人',
                dataIndex: 'collectorName',
                key: 'collectorName',
                render(text) {
                    return text;
                    // const { personData } = _this.props;
                    // const obj = personData.find(item => Number(item.value) === Number(text));
                    // console.log(obj);
                    // return  obj ? obj['name'] : '';
                }
            },
            {
                title: '逾期时间',
                dataIndex: 'expireTime',
                key: 'expireTime',
                render(text) {
                    return moment(Number(text) * 1000).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            {
                title: '操作',
                dataIndex: 'id',
                key: 'id',
                render(text, record) {
                    const { userId, enabled } = record;
                    return (
                        <div>
                            <Tooltip title={'查看详情'}>
                                <Icon type="exception" onClick={() => _this.handleLookDetail(text, userId)} className={styles.operatorWrapper}/>
                            </Tooltip>
                            {
                                enabled ? (Number(enabled) === 1 ?
                                <Tooltip title={'滞纳金减免'}>
                                    <Icon type="file-text" onClick={() => _this.showModal(text, record)} className={styles.operatorWrapper} style={{marginLeft: '10px'}} />
                                </Tooltip>
                                : null) : null
                            }
                        </div>
                    );
                }
            }
        ];
    }
    //查看详情
    handleLookDetail = (id, userId) => {
        const { history: { push } } = this.props;
        push(`/overdueList/${id}`, { userId });
    }

    // 减免金额
    showModal = (text, record) => {
        this.setState({
            record,
            breaksVisible: true
        });
    }

    //选择订单
    onSelectChange = (selectedRowKeys) => {
        const { changeSelectKeys } = this.props;
        changeSelectKeys(selectedRowKeys);
    }
    //点击分配订单
    distributeOrder = () => {
        // const { selectedRowKeys } = this.state;
        const { selectKeys } = this.props;
        const { changeModalVisible, personData } = this.props;
        //是否有选中订单
        const isSelected = selectKeys.length > 0;
        if(!isSelected) {
            message.warn('请先选择订单');
            return;
        }
        if (personData.length === 0) {
            message.warn('暂无催收人');
            return;
        }
        //打开催收人弹框
        changeModalVisible(true);
    }

    //搜索
    handleSearch = (obj) => {
        const { setSearchParams, getTableData } = this.props;
        setSearchParams(obj);
        const params = this.convertParams(obj);
        getTableData({ ...params, pageNum: 1, pageSize:10 });
    }
    //分页
    handlePageChange = (info) => {
        const { pageSize, current } = info;
        const { getTableData, searchParams } = this.props;
        const params = this.convertParams(searchParams);
        getTableData({ ...params, pageSize, pageNum: current });
    }

    //关闭催收人弹框
    onModalCancel = () => {
        const { changeModalVisible } = this.props;
        changeModalVisible(false);
    }
    //点击弹框确定按钮,分配订单
    onModalOk = (obj) => {
        // const { selectedRowKeys } = this.state;
        // const { selectKeys } = this.props;
        const { distributeOrder, getTableData, searchParams, selectKeys, tableData: { pagination }, personType } = this.props;
        // const collectorId = obj['person'];
        let key = personType === 'group' ? 'departmentId' : 'collectorId';
        //todo 分配订单回调？
        distributeOrder({ disIds: selectKeys.join(','), [key]: obj['person'] }, () => {
            let params = this.convertParams(searchParams);
            params = { ...params, pageSize: pagination['pageSize'] || 10, pageNum: pagination['current'] || 1 };
            getTableData(params);
        });
    }



    componentDidMount() {
        const { getTableData, tableData: { pagination }, searchParams, getPerson, personData } = this.props;
        let params = this.convertParams(searchParams);
        params = { ...params, pageSize: pagination['pageSize'] || 10, pageNum: pagination['current'] || 1 };
        //如果store中没有催收人信息，则取请求催收人列表
        //todo 异步请求顺序
        // if (personData.length === 0) {
        //     getPerson({ roleId: 8 }, () => {
        //         getTableData(params);
        //     });
        // } else {
        //     getTableData(params);
        // }
        getPerson({ roleId: 8 }, () => {
            getTableData(params);
        });

    }
    //todo 是否清理列表以及选择数据
    componentWillUnmount() {
        // const { location: { pathname } } = this.props;
        // const isOk = pathname.indexOf()
    }

    handleok = (data) => {
        // console.log(data)
        var Amount = data.reduceAmount.toString();
        if (data.remark!=="" && Amount!==""){
            axios({
                url: '/hs/admin/orderReduce/reduceSetting',
                method: 'post',
                data: {
                    orderNo: data.orderNo,
                    reduceAmount: data.reduceAmount,
                    remark: data.remark
                }
            }).then((res) => {
                if(res) {
                    // console.log(res)
                }
            })
            this.setState({
                breaksVisible: false,
            })
        } else {
            message.warn('减免金额、备注 均不能为空');
        }
    }

    handleCancel = () => {
        this.setState({
            breaksVisible: false,
        });
    }

    // 批量分配订单
    showOrderModal = () => {
        this.setState({
            isOrderModalView: true,
        })
    }
    orderModalCancel = () => {
        this.setState({
            isOrderModalView: false,
        })
    }

    render(){
        const {
            tableData: { data, pagination },
            loading,
            searchParams,
            visible,
            selectKeys,
            personData
        } = this.props;
        const rowSelection = {
            selectedRowKeys: selectKeys,
            onChange: this.onSelectChange
        };

        //new 
        let { isOrderModalView } = this.state;
        return (
            <div>
                <SearchList handleSubmit={this.handleSearch} params={searchParams} personData={personData}/>
                <div>
                    <Button type={'primary'} onClick={this.distributeOrder}>重新分配订单</Button>

                    {/* 批量分配订单 */}
                    <Button type="primary" onClick={this.showOrderModal} style={{marginLeft:30}}>批量分配订单</Button>
                </div>

                <OverdueOrderUrgeReqList
                    visible={isOrderModalView}
                    onCancel={this.orderModalCancel}
                    unOrderTotalNum={pagination.total}
                    urgePerson={personData}
                    params={searchParams}
                    dataSource={data}
                />

                <CommonTable
                    columns={this.columns}
                    pagination={pagination}
                    handlePageChange={this.handlePageChange}
                    loading={loading}
                    dataSource={data}
                    rowSelection={rowSelection}
                />
                <UrgePersonModal
                    visible={visible}
                    urgePerson={personData}
                    onModalOk={this.onModalOk}
                    onModalCancel={this.onModalCancel}
                />
                <FormDemo data={this.state.record} visible={this.state.breaksVisible} handleok={this.handleok} handleCancel={this.handleCancel} />
            </div>
        );
    }
}
const mapStateToProps = (state) => {
    const { afterLoanManageState: { overdueListState } } = state;
    return {
        tableData: overdueListState['data'],
        loading: overdueListState['loading'],
        searchParams: overdueListState['params'],
        personData: overdueListState['personData'],
        selectKeys: overdueListState['selectKeys'],
        visible: overdueListState['visible'],
        personType: overdueListState['personType']
    }
}
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        getTableData: overdueListAction.odlGetTableData,
        setTableData: overdueListAction.odlSetTableData,
        setSearchParams: overdueListAction.odlChangeSearchParams,
        getPerson: overdueListAction.odlGetPerson,
        changeModalVisible: overdueListAction.odlChangeModalVisible,
        distributeOrder: overdueListAction.odlDistributeOrder,
        changeSelectKeys: overdueListAction.odlChangeSelectKey
    }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(OverdueList);